package com.gxa.p2p.controller;

import com.gxa.p2p.businessExceptionCode.ErrorCode;
import com.gxa.p2p.exception.BusinessException;
import com.gxa.p2p.pojo.LoginLog;
import com.gxa.p2p.service.LoginAndLogoutInfoService;
import com.gxa.p2p.util.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * 登录管理 当前用户登录信息查询
 *
 * @author Longlin_Feng @date 2020/8/1
 */
@Controller
@CrossOrigin
@RequestMapping("/log")
@Api(value = "用户登录历史", tags = "用户登录历史信息接口")
public class LoginAndLogoutInfoController {

  @Resource private LoginAndLogoutInfoService loginAndLogoutInfoService;

  /**
   * 查询当前用户登录信息
   *
   * @param currentUserId 当前用户id
   * @return Map<String , Object>
   */
  @GetMapping("/history")
  @ResponseBody
  @ApiOperation(value = "当前用户登录历史查询", httpMethod = "get", response = List.class)
  @ApiImplicitParam(
      name = "currentUserId",
      value = "当前用户id",
      required = true,
      paramType = "Integer")
  public Map<String, Object> findLoginHistory(@RequestParam("id") Integer currentUserId) {
    System.out.println("currentUserId: " + currentUserId);
    // 调用服务层接口,返回登录日志对象
    List<LoginLog> loginHistory = loginAndLogoutInfoService.findLoginHistory(currentUserId);
    if (loginHistory != null) {
      // 响应信息
      MapUtil mapUtil = new MapUtil();
      mapUtil.setCode(0);
      mapUtil.put("loginHistory", loginHistory);
      return mapUtil.getMap();
    } else {
      throw new BusinessException(ErrorCode.FAILED);
    }
  }

  /**
   * 登出接口
   *
   * @param currentUserId 当前用户ID
   * @return Map<String , Object>
   */
  @GetMapping("/logout")
  @ResponseBody
  @ApiOperation(value = "用户登出接口(记录登出时间)", httpMethod = "get", response = Map.class)
  @ApiImplicitParam(name = "id", value = "当前用户ID", required = true, paramType = "Integer")
  public Map<String, Object> logout(@RequestParam("id") Integer currentUserId) {

    // 调用服务层登出接口
    if (loginAndLogoutInfoService.logout(currentUserId)) {
      MapUtil mapUtil = new MapUtil();
      mapUtil.setCode(0);

      return mapUtil.getMap();
    } else {
      throw new BusinessException(ErrorCode.FAILED);
    }
  }
}
